import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'


const service = axios.create({
  baseURL: 'https://peipao.tiansuanshuke.com',
  //baseURL: 'https://peipao-api-test.tiansuanshuke.com',
  timeout: 5000
})


service.interceptors.request.use(
  config => {

    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }

    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)


service.interceptors.response.use(

  response => {
    const res = response.data;


    if (res?.success) {
      //只有是success是true的才是正常处理的
      return res;
    } else if (!res?.success) {
      //代表有错误，直接提示消息
      Message({
        message: res?.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      //如果是登录过期，提示重新登录
      if (res.code === 101003) {
        MessageBox.confirm('登录过期，是否从新登录？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }

      // //不会进then和catch，以及finally,终断promise链
      // return new Promise(() => { })



      // 抛出错误，控制台会爆红，但会被 finally 捕获,不进入then和catch
      throw new Error('业务错误，中断 Promise 链');
    }


  },
  error => {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
